package com.roc.web.action.susMerinfo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.MerinfoSearchBean;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.EtbSysCardBinno;
import com.roc.pojo.Operators;
import com.roc.pojo.susesMerinfo;
import com.roc.service.IExcelService;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.MerchantStatus;
import com.roc.util.constant.Role;
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
@Namespace("/susMerinfo")
public class SusMerinfoAction extends PaginationBaseAction{
	private Logger logger=LogManager.getLogger(SusMerinfoAction.class);
	private SusMerinfoSearchCondition searchCondition;
	private susesMerinfo susMerinfo;
	
	private InputStream excelFile;
	private String  excelName;
	
	private File upload;
		
    private String msg;
		
	@Autowired
	IExcelService excelService;
	@Autowired
	IPagenitionService pagenitionService;
	
	@Autowired
	IMerchantServices iMerchantServices;
	
	@Action(value = "init", results = { @Result(name = "success", location = "/pages/susMerinfo/query.jsp")
    })
	public String init(){
		return SUCCESS;
	}
	
	@Action(value = "query", 
			results = { @Result(name = "success", location = "/pages/susMerinfo/query.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String query(){
		Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);

		if(searchCondition==null){
			searchCondition=(SusMerinfoSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new SusMerinfoSearchCondition();
			}
		}
		try {
			
			init();
			
			int rows=pagenitionService.count(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAll(searchCondition, calcuStart(getCurrentPage()),Constance.PAGE_MAX_SIZE);
			}
			List<susesMerinfo> msList=new ArrayList<susesMerinfo>();
			dealWith(msList,searchRsList);
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute("msList", msList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
			
		}catch(ServiceException e){
			logger.error(e.getMessage(),e);
			addActionError(e.getMessage());
		}
		
		return SUCCESS;
	}
	
	@Action(value="export",results = {@Result(name="success",type="stream"
			,params = { "contentType", "application/vnd.ms-excel", "inputName",  
			            "excelFile","contentDisposition",  "attachment;filename=${excelName}.xls",
			            "bufferSize", "1024*3" }),@Result(name="error",location="/pages/susMerinfo/query.jsp") }) 
	public String export(){
		Operators op=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		if(searchCondition==null){
			searchCondition=(SusMerinfoSearchCondition)getSearchConditionFromSession();
			if(searchCondition==null){
				searchCondition=new SusMerinfoSearchCondition();
			}
		}
		try{

			//searchCondition.setAgentId(op.getId());
			int rows=pagenitionService.count(searchCondition);
			if(rows>0){
				searchRsList=pagenitionService.findAll(searchCondition, calcuStart(getCurrentPage()), rows);
			}
			List<susesMerinfo> msList=new ArrayList<susesMerinfo>();
			dealWith(msList,searchRsList);
			
			HSSFWorkbook work=excelService.susMerinfoExcel(msList);
			 ByteArrayOutputStream output = new ByteArrayOutputStream();  
			         work.write(output);  
			   
			        byte[] ba = output.toByteArray();  
			         excelFile = new ByteArrayInputStream(ba);  
			         output.flush();  
			         output.close();  
		}catch(Exception e){
			logger.info("######导出Excel失败######");
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;
	}
	
	private List<susesMerinfo> dealWith(List<susesMerinfo> msList,List<Object> searchRsList){
		if(searchRsList.size()>0 && searchRsList!=null){
			
			Iterator iterator=searchRsList.iterator();
			while (iterator.hasNext()) {
				Object[] obj= (Object[])iterator.next();
				susesMerinfo  msb=new susesMerinfo(); 
				msb.setCardNo(Constance.Null2EmptyTrim(obj[0]));
				msb.setBusinessLiscences(Constance.Null2EmptyTrim(obj[1]));
				msb.setMerinfo(Constance.Null2EmptyTrim(obj[2]));
				msb.setAreaCode(Constance.Null2EmptyTrim(obj[3]));
				msb.setBusiness(Constance.Null2EmptyTrim(obj[4]));
				msb.setCol1(Constance.Null2EmptyTrim(obj[5]));
				msList.add(msb);
			}
		}
		return msList;
		
	}

	public String getExcelName() {
		String excelName="风险商户"+Constance.formateDate();
		 
			try {
				excelName = new String(excelName.getBytes(),"ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				logger.info("生成excel名称失败了！");
			}
		 
		return  excelName;
		
	}
	@Action(value = "add", 
			results = { @Result(name = "success", location = "/pages/susMerinfo/add.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String add(){
		
		return SUCCESS;
	}
	@Action(value = "addSave", 
			results = { @Result(name = "success", location = "/pages/susMerinfo/query.jsp"),
			@Result(name = "error", location = "/error.jsp")
    })
	public String addSave(){
		try{
			iMerchantServices.saveKyMer(susMerinfo);
		}catch(Exception e){
			logger.info("######保存失败######");
			addActionError(e.getMessage());
			return ERROR;
		}
		return query();
	}
	
	@Action(value = "merinfoImportInit", results = { @Result(name = "success", location = "/pages/susMerinfo/subMerinfoImport.jsp") })
	public String merinfoImportInit() throws Exception {
		return SUCCESS;
	}

	
	@Action(value = "merinfoImport", interceptorRefs = {
			@InterceptorRef(value = "token"),
			@InterceptorRef(value = "rocDefaultStack", params = {
					"fileUpload.allowedExtensions", "xlsx",
					"fileUpload.maximumSize", "100000000" }) }, results = {
			@Result(location = "/pages/susMerinfo/subMerinfoImport.jsp"),
			@Result(name = "error", location = "/error.jsp"),
			@Result(name = "invalid.token", location = "/error.jsp") })
	public String merinfoImport() throws Exception {

		if (upload == null) {
			msg = "请选择文件";
			return SUCCESS;
		}

		try {
			excelImpl();
			addActionError("导入商户成功");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}

		return SUCCESS;
	}
	
	public void excelImpl() throws Exception {


		// 构造 XSSFWorkbook 对象，strPath 传入文件路径
		XSSFWorkbook xwb = new XSSFWorkbook(upload.getPath());
		// 读取第一章表格内容
		XSSFSheet sheet = xwb.getSheetAt(0);
		// 定义 row、cell
		XSSFRow row;
		
		// 循环输出表格中的内容
		for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
			row = sheet.getRow(i);
			susesMerinfo sub  = new susesMerinfo();
			for (int j = row.getFirstCellNum(); j < 6; j++) {
				
				String cell = "";
			
				// 通过 row.getCell(j).toString() 获取单元格内容
				if (row.getCell(j) != null) {
					//cell = Constance.Null2EmptyTrim(row.getCell(j).toString());
					row.getCell(j).setCellType(Cell.CELL_TYPE_STRING);//设置成字符格式原样读取
					cell = Constance.Null2EmptyTrim(row.getCell(j).getStringCellValue());
				}
				switch (j) {
				case 0:
					sub.setCardNo(cell);
					break;
				case 1:
					sub.setBusinessLiscences(cell);
					break;
				case 2:
					sub.setMerinfo(cell);
					break;
				case 3:
					sub.setBusiness(cell);
					break;
				case 4:
					sub.setAreaCode(cell);
					break;
				case 5:
					sub.setCol1(cell);
					break;
				default:
					break;
				}
				
			}
			
			iMerchantServices.saveKyMer(sub);
		}

	}
	
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return this.searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		// TODO Auto-generated method stub
		this.searchCondition=(SusMerinfoSearchCondition) searchCondition;
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		// TODO Auto-generated method stub
		getSession().setAttribute(SEARCH_SESSION_SUSMERINFO_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (BaseSearchCondition) getSession().getAttribute(SEARCH_SESSION_SUSMERINFO_QUERY);
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return null;
	}

	public SusMerinfoSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(SusMerinfoSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}

	public void setExcelName(String excelName) {
		this.excelName = excelName;
	}

	public File getUpload() {
		return upload;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public susesMerinfo getSusMerinfo() {
		return susMerinfo;
	}

	public void setSusMerinfo(susesMerinfo susMerinfo) {
		this.susMerinfo = susMerinfo;
	}
	
	

}
